package com.design.springboot.booksharing.controller;

import com.design.springboot.booksharing.bean.ApiResult;
import com.design.springboot.booksharing.component.ApiResultComponent;
import com.design.springboot.booksharing.enums.ApiResultCodeEnum;
import com.design.springboot.booksharing.utils.FileUtils;
import com.design.springboot.booksharing.utils.Strings;
import com.design.springboot.booksharing.utils.snowflake.Snowflake;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * 通用请求处理
 *
 * @author admin
 */
@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    Snowflake snowflake;

    @Resource
    ApiResultComponent apiResultComponent;

    private String baseDir;

    public CommonController() {
        this.baseDir = FileUtils.getFileBaseDir();
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public ApiResult<String> uploadFile(MultipartFile file) throws Exception {
        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());

            String nextId = snowflake.nextId().toString();

            // 上传并返回新文件名称
            String fileName = nextId + "." + extension;

            file.transferTo(new File(baseDir, fileName));
            return apiResultComponent.success(fileName);
        } catch (Exception e) {
            return apiResultComponent.error(ApiResultCodeEnum.UPLOAD_ERROR);
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(Strings.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String filePath = this.baseDir + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));

            FileUtils.write(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     */
    @GetMapping("common/image")
    public void previewPicture(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(Strings.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String filePath = this.baseDir + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            FileUtils.write(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
